package service.Impl;

import entity.UserInfoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import service.Interface.WsBindingInterface;

/**
 * Created by thinkjoy on 2017/8/31.
 */
@Service
public class WsBindingImpl implements WsBindingInterface {

    private String openid;
    @Autowired
    private WsUserImpl wsUser;

    /**
     * 获取点击菜单后的openid
     * @return
     */
    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }

    /**
     * 当同时有多个微信号绑定一个用户时，先前绑定的记录将被删除，只记录最新绑定的微信号,先前绑定的微信号将不接收任何消息
     * 若再想重新绑定旧的微信号，需要重新登录
     * @param workerid
     * @param openid
     * @return
     */
    @Override
    public String updateUserForOpenid(String workerid, String openid) {
        try {

            UserInfoEntity userInfoEntity=wsUser.findUserInfoAll(workerid,openid);
            if (userInfoEntity==null){
                String opid=wsUser.findSingleUserInfo(workerid);
                String wid=wsUser.findWorkerIDforOpenId(openid);
                /**
                 * 当A用户换用另一个未绑定过的微信登录的时候，会解除原微信绑定的记录
                 */
                if (!StringUtils.isEmpty(opid) && !opid.equals(openid)){
                   wsUser.deleteUserByOpenid(opid);
                }
                /**
                 * 当A用户在B用户微信上登录的时候，会解除B用户微信的所有绑定记录
                 */
                if(!StringUtils.isEmpty(wid) && !wid.equals(workerid)){
                    wsUser.deleteUserByOpenid(openid);
                }
                //重新绑定
                int num=wsUser.saveAllUserInfo(workerid,openid);
                if (num>0){
                    return "0";
                }else{
                    return "1";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
       return "2";
    }

    public String deleteUser(){
        int num=wsUser.deleteUserByOpenid(getOpenid());
        if (num>0){
            return "0";
        }else {
            return "1";
        }
    }
}
